import json
import os

class JsonDatabase:
    def __init__(self, file_path):
        self.file_path = os.path.join(os.path.dirname(__file__),file_path)
        self.data = self._load_data()

    def _load_data(self):
        try:
            with open(self.file_path, 'r') as file:
                return json.load(file)
        except (FileNotFoundError, json.JSONDecodeError):
            return {}

    def _save_data(self):
        with open(self.file_path, 'w') as file:
            json.dump(self.data, file, indent=4)

    def insert(self, table, record):
        if table not in self.data:
            self.data[table] = []
        self.data[table].append(record)
        self._save_data()

    def select(self, table, condition=None):
        if table not in self.data:
            return []
        if condition is None:
            return self.data[table]
        result = []
        for record in self.data[table]:
            if all(record.get(key) == value for key, value in condition.items()):
                result.append(record)
        return result

    def update(self, table, condition, new_values):
        if table not in self.data:
            return
        for record in self.data[table]:
            if all(record.get(key) == value for key, value in condition.items()):
                for key, value in new_values.items():
                    record[key] = value
        self._save_data()

    def delete(self, table, condition):
        if table not in self.data:
            return
        self.data[table] = [record for record in self.data[table]
                            if not all(record.get(key) == value for key, value in condition.items())]
        self._save_data()


# 创建一个JsonDatabase实例
# db = JsonDatabase('user.json')

# 插入数据
# db.insert('users', {'id': 1, 'name': 'Alice', 'age': 30})
# db.insert('users', "123")

# 查询数据
# print(db.select('users',{'username':'starsac'})[0].get("username"))

# # 更新数据
# db.update('users', {'id': 1}, {'age': 31})
# print(db.select('users', {'id': 1}))

# # 删除数据
# db.delete('users', {'id': 2})
# print(db.select('users'))